package com.fourcitizens.playas

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
import org.grails.plugins.csv.*

import com.sun.tools.javac.util.Log;

class BeachesCSVLoaderException {
	String message
	String theFilePath
}

class BeachesCSVLoaderService {

    static transactional = true
	
	def countryService
	def provinceService
	def townService
	def beachService

	def loadBeachesCSVUnefficiently(File theCSV) {
		def mySeparatorChar = ";"
		def attributesOrderMap = [
			photo: 0,
			province : 1,
			town : 2,
			name : 3,
			description : 4,
			length : 5,
			mediumWidth : 6,
			promenade : 7,
			anchorageArea : 8,
			nudist : 9,
			occupation : 10,
			urbanization : 11,
			composition : 12,
			sandType : 13,
			bathingConditions : 14,
			vegetation : 15,
			blueFlag : 16,
			protectedArea : 17,
			accessSignaling : 18,
			disabledAccess : 19,
			toilets : 20,
			showers : 21,
			phone : 22,
			paperBin : 23,
			cleaningService : 24,
			gateways : 25,
			umbrellasRental : 26,
			sunbedRental : 27,
			yatchRental : 28,
			spaKiosks : 29,
			yatchClub : 30,
			divingArea : 31,
			latitude : 32,
			longitude : 33
			]
		
		def beachProperties = Beach.properties
		def countryName = "Spain"
		def beachPropertiesMap = [:]
		int rows = 0
		
		theCSV.toCsvReader(['charset':'ISO-8859-1','separatorChar':';','strictQuotes':false]).eachLine { tokens ->
			
			def beachName = tokens[attributesOrderMap['name']]
			def townName = tokens[attributesOrderMap['town']]
			def provinceName =  tokens[attributesOrderMap['province']]
			def neeededAttributesMap = attributesOrderMap.minus([province : 1,town : 2,name : 3])
			
			neeededAttributesMap.each { entry ->
				def readBeachProperty = tokens[entry.value] 
				
				String valueUTF8 = new String(readBeachProperty.getBytes("UTF-8"))
				
				beachPropertiesMap.putAt(entry.key,valueUTF8)
			}
			
			//log.debug("Saving beach... $beachName")
			beachService.createBeach(countryName,provinceName,townName,beachName,beachPropertiesMap)
			rows++
			println rows
		}
		
		println 'Total beaches: ' + rows
	}
}
